#!/usr/bin/env python
'''
    Automatic Update Hook for MakeMKV/Remote MakeMKV
    
    @author     David Lasley, dave -at- dlasley -dot- net
    @website    https://dlasley.net/blog/projects/remote-makemkv/
    @package    remote-makemkv
    @license    GPLv3
    @version    $Id:$
'''
import os
import urllib2
import re
import subprocess
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)

#  Uncomment for release
#logging.basicConfig(format='%(asctime)s %(message)s', level=logging.ERROR)

#   Detect root, error if not (ignore on Windows?)
try:
    if os.getuid() != 0:
        raise Exception('Must run as root!')
except AttributeError:
    pass #< Windows

class update_makemkv(object):
    ''' MakeMKV Updater Object  '''
    
    URL = 'http://www.makemkv.com/forum2/viewtopic.php?f=3&t=224'
    FILE_REGEX = re.compile( '%s%s' % (
        '(https?://(www)?\.makemkv\.com/download/makemkv\-',
        '(bin|oss)\-(\d\.){3}tar\.gz)'
    ))
    VERSION_REGEX = re.compile('MakeMKV v((\d\.){2}\d)')
        
    def __init__(self, ):
        '''
            Initialize, run a version check
            Sets    self.up_to_date     bool   
        '''
        curr_ver = self.chk_curr_ver()
        parsed_page = self.__parse_page()
        self.up_to_date =  self.compare_versions(curr_ver,
                                     parsed_page.items()[0]['version'])
    
    def install_new(self, ):
        '''
            Install new MakeMKV version
            @return bool    Success?
        '''
        for release, version_info in parsed_page.iteritems():
            version = version_info['version']
            logging.debug('Opening "%s%' % version_info['url'])
            tar_file = urllib2.urlopen(version_info['url']).read()
            logging.debug('Writing to "%s.tar.gz"' % release)
            fh = open(release + '.tar.gz', 'w')
            fh.write(tar_file)
            fh.close()
            logging.debug('Untar to "%s"' % release)
            try:
                subprocess.check_output([
                    'tar', '-xvf', release + '.tar.gz'
                ])  
            except subprocess.CalledProcessError as e:
                logging.error('Failed to untar "%s"' %
                              release + '.tar.gz')
                raise
        
        #   Install OS
        for pkg_type in 'oss', 'bin':
            pass
        
    
    def chk_curr_ver(self, ):
        '''
            Check current MakeMKV version
            
            @return str MakeMKV version
        '''
        try:
            subprocess.check_output([
                'makemkvcon', '-r', 'info', '--noscan',
            ])  
        except subprocess.CalledProcessError as e:
            cmd_return = e.output
            
        return self.VERSION_REGEX.findall(cmd_return)[0][0]
    
    def compare_versions(self, ver_1, ver_2, ):
        '''
            Compare Two versions, return False if ver_1 is lower
            
            @param  ver_1   list    Current version
            @param  ver_2   list    Possible new version
            @return bool    True if ver_1 is up to date
        '''
        ver_1, ver_2 = ver_1.split('.'), ver_2.split('.')
        for i in xrange(len(ver_1)):
            if int(ver_1[i]) < int(ver_2[i]):
                return False
        return True
    
    def __parse_page(self, ):
        '''
            Parse forum page to look for downloads
            
            @return dict    key is full release name; values - url, tar_name, version
        '''
        logging.debug('Opening "%s" to parse' % self.URL)
        url_matches = list(set(self.FILE_REGEX.findall(
            urllib2.urlopen(self.URL, ).read())))
        releases = {}
        
        for url in url_matches:
            tar_name = os.path.basename(url[0])
            release = tar_name.replace('.tar.gz', '')
            version = re.findall('((\d\.){2}\d)', release)[0][0]
            releases[release] = { 'tar_name':tar_name, 'url':url[0],
                                  'version':version,
                                  }
            
        return releases
        
        
        
if __name__ == '__main__':
    print update_makemkv().up_to_date 